import type { ApiResponse, HttpTransaction, Rule, ProxyConfig } from '../types';

const API_BASE_URL = 'http://127.0.0.1:12280/api';

class ApiClient {
  private baseURL: string;

  constructor(baseURL: string = API_BASE_URL) {
    this.baseURL = baseURL;
  }

  // 通用请求方法
  private async request<T>(
    endpoint: string,
    options: RequestInit = {}
  ): Promise<ApiResponse<T>> {
    const url = `${this.baseURL}${endpoint}`;
    
    const defaultOptions: RequestInit = {
      headers: {
        'Content-Type': 'application/json',
        ...options.headers,
      },
    };

    const response = await fetch(url, { ...defaultOptions, ...options });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.error || `HTTP ${response.status}: ${response.statusText}`);
    }

    return response.json();
  }

  // GET 请求
  private async get<T>(endpoint: string): Promise<ApiResponse<T>> {
    return this.request<T>(endpoint, { method: 'GET' });
  }

  // POST 请求
  private async post<T>(endpoint: string, data?: any): Promise<ApiResponse<T>> {
    return this.request<T>(endpoint, {
      method: 'POST',
      body: data ? JSON.stringify(data) : undefined,
    });
  }

  // PUT 请求
  private async put<T>(endpoint: string, data?: any): Promise<ApiResponse<T>> {
    return this.request<T>(endpoint, {
      method: 'PUT',
      body: data ? JSON.stringify(data) : undefined,
    });
  }

  // DELETE 请求
  private async delete<T>(endpoint: string): Promise<ApiResponse<T>> {
    return this.request<T>(endpoint, { method: 'DELETE' });
  }

  // 获取HTTP交互记录 - 已移除，通过WebSocket实时获取数据

  // 获取单个交互记录
  async getTransaction(id: string): Promise<ApiResponse<HttpTransaction>> {
    return this.get<HttpTransaction>(`/transactions/${id}`);
  }

  // 清空所有记录
  async clearAllRecords(): Promise<ApiResponse<{ success: boolean; message: string }>> {
    return this.delete<{ success: boolean; message: string }>('/transactions');
  }

  // 获取规则列表
  async getRules(): Promise<ApiResponse<Rule[]>> {
    return this.get<Rule[]>('/rules');
  }

  // 创建规则
  async createRule(rule: Omit<Rule, 'id' | 'createdAt' | 'updatedAt'>): Promise<ApiResponse<Rule>> {
    return this.post<Rule>('/rules', rule);
  }

  // 更新规则
  async updateRule(id: string, rule: Partial<Rule>): Promise<ApiResponse<Rule>> {
    return this.put<Rule>(`/rules/${id}`, rule);
  }

  // 删除规则
  async deleteRule(id: string): Promise<ApiResponse<{ success: boolean }>> {
    return this.delete<{ success: boolean }>(`/rules/${id}`);
  }

  // 测试规则
  async testRule(rule: Rule, transactionId: string): Promise<ApiResponse<{ matched: boolean }>> {
    return this.post<{ matched: boolean }>('/rules/test', { rule, transactionId });
  }

  // 获取代理状态
  async getProxyStatus(): Promise<{ enabled: boolean; running: boolean; httpPort: number; httpsPort: number; interceptHttps: boolean }> {
    const url = `${this.baseURL}/proxy/status`;
    const response = await fetch(url, {
      method: 'GET',
      mode: 'cors',
      headers: {
        'Accept': 'application/json',
      },
    });
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
    
    return response.json(); // 后端直接返回状态对象，不是包装格式
  }

  // 切换代理开关
  async toggleProxy(): Promise<{ success: boolean; status: string }> {
    const url = `${this.baseURL}/proxy/toggle`;
    const response = await fetch(url, {
      method: 'POST',
      mode: 'cors',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
    });
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }
    
    return response.json(); // 后端直接返回结果对象
  }

  // 更新代理配置
  async updateProxyConfig(config: Partial<ProxyConfig>): Promise<ApiResponse<{ running: boolean; config: ProxyConfig }>> {
    return this.put<{ running: boolean; config: ProxyConfig }>('/proxy/config', config);
  }

  // 获取WebSocket客户端信息
  async getWebSocketClients(): Promise<ApiResponse<{ count: number; clients: any[] }>> {
    return this.get<{ count: number; clients: any[] }>('/websocket/clients');
  }

  // 清理旧记录
  async cleanupOldRecords(days = 30): Promise<ApiResponse<{ success: boolean; message: string }>> {
    return this.post<{ success: boolean; message: string }>('/cleanup', { days });
  }
}

// 创建单例实例
export const apiClient = new ApiClient();
export default apiClient; 